'''
Author: duliang thinktanker@163.com
Date: 2025-10-07 21:45:28
LastEditors: duliang thinktanker@163.com
LastEditTime: 2025-10-07 21:48:07
FilePath: 
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
import librosa
import numpy as np
import matplotlib.pyplot as plt
# 设置matplotlib支持中文显示
plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False

# 1. 加载音频（建议使用高采样率，如 44.1kHz 或 48kHz）
y, sr = librosa.load('audio_11236e83a9.mp3', sr=44100)  # 替换为你的文件

# 2. 分帧（例如每帧 0.1 秒）
frame_length = int(0.1 * sr)  # 100ms 帧长
hop_length = frame_length // 2

# 3. 提取特征（按帧）
rms = librosa.feature.rms(y=y,
                          frame_length=frame_length,
                          hop_length=hop_length)[0]
zcr = librosa.feature.zero_crossing_rate(y,
                                         frame_length=frame_length,
                                         hop_length=hop_length)[0]
spectral_centroids = librosa.feature.spectral_centroid(
    y=y, sr=sr, n_fft=frame_length, hop_length=hop_length)[0]
spectral_bandwidth = librosa.feature.spectral_bandwidth(
    y=y, sr=sr, n_fft=frame_length, hop_length=hop_length)[0]

# 4. 时间轴
frames = range(len(rms))
t = librosa.frames_to_time(frames, sr=sr, hop_length=hop_length)

# 5. 可视化
fig, axs = plt.subplots(4, 1, figsize=(12, 10), sharex=True)
axs[0].plot(t, rms)
axs[0].set_ylabel('RMS 能量')
axs[1].plot(t, zcr)
axs[1].set_ylabel('过零率')
axs[2].plot(t, spectral_centroids)
axs[2].set_ylabel('频谱质心 (Hz)')
axs[3].plot(t, spectral_bandwidth)
axs[3].set_ylabel('频谱带宽 (Hz)')
axs[3].set_xlabel('时间 (秒)')
plt.suptitle('电机声音特征随时间变化')
plt.tight_layout()
plt.show()
